﻿using System;
using System.Collections.Generic;
using System.Linq;

/// <summary>
/// 用户实体类（封装用户数据）
/// </summary>
public class User
{
    /// <summary>
    /// 用户唯一标识（主键）
    /// </summary>
    public int Id { get; set; }

    /// <summary>
    /// 用户名
    /// </summary>
    public string Username { get; set; } = string.Empty;

    /// <summary>
    /// 密码（实际开发需加密存储）
    /// </summary>
    public string Password { get; set; } = string.Empty;

    /// <summary>
    /// 邮箱
    /// </summary>
    public string Email { get; set; } = string.Empty;

    /// <summary>
    /// 注册时间
    /// </summary>
    public DateTime RegisterTime { get; set; } = DateTime.Now;

    /// <summary>
    /// 重写 ToString 方便调试输出
    /// </summary>
    public override string ToString()
    {
        return $"Id: {Id}, Username: {Username}, Email: {Email}, RegisterTime: {RegisterTime:yyyy-MM-dd HH:mm:ss}";
    }
}

/// <summary>
/// 用户服务接口（定义增删改查契约）
/// </summary>
public interface IUserService
{
    /// <summary>
    /// 新增用户
    /// </summary>
    /// <param name="user">待新增的用户对象</param>
    /// <returns>新增成功返回 true，失败返回 false</returns>
    bool AddUser(User user);

    /// <summary>
    /// 根据 ID 删除用户
    /// </summary>
    /// <param name="userId">用户唯一标识</param>
    /// <returns>删除成功返回 true，失败返回 false</returns>
    bool DeleteUser(int userId);

    /// <summary>
    /// 更新用户信息
    /// </summary>
    /// <param name="user">包含更新后信息的用户对象（需指定有效 Id）</param>
    /// <returns>更新成功返回 true，失败返回 false</returns>
    bool UpdateUser(User user);

    /// <summary>
    /// 根据 ID 查询单个用户
    /// </summary>
    /// <param name="userId">用户唯一标识</param>
    /// <returns>查询到的用户对象，未找到返回 null</returns>
    User? GetUserById(int userId);

    /// <summary>
    /// 查询所有用户
    /// </summary>
    /// <returns>所有用户的集合</returns>
    List<User> GetAllUsers();
}

/// <summary>
/// 用户服务实现类（实现 IUserService 接口的 CRUD 方法）
/// </summary>
public class UserServiceImpl : IUserService
{
    // 内存集合模拟数据库存储
    private readonly List<User> _userList = new List<User>();

    /// <summary>
    /// 新增用户（校验用户名和邮箱唯一）
    /// </summary>
    public bool AddUser(User user)
    {
        if (user == null)
        {
            Console.WriteLine("新增失败：用户对象不能为空！");
            return false;
        }

        bool isUsernameExists = _userList.Any(u => u.Username.Equals(user.Username, StringComparison.OrdinalIgnoreCase));
        bool isEmailExists = _userList.Any(u => u.Email.Equals(user.Email, StringComparison.OrdinalIgnoreCase));

        if (isUsernameExists)
        {
            Console.WriteLine($"新增失败：用户名「{user.Username}」已存在！");
            return false;
        }

        if (isEmailExists)
        {
            Console.WriteLine($"新增失败：邮箱「{user.Email}」已存在！");
            return false;
        }

        // 生成自增 ID
        user.Id = _userList.Any() ? _userList.Max(u => u.Id) + 1 : 1;
        user.RegisterTime = DateTime.Now;

        _userList.Add(user);
        Console.WriteLine($"新增成功：{user}");
        return true;
    }

    /// <summary>
    /// 根据 ID 删除用户
    /// </summary>
    public bool DeleteUser(int userId)
    {
        User? userToDelete = _userList.FirstOrDefault(u => u.Id == userId);

        if (userToDelete == null)
        {
            Console.WriteLine($"删除失败：未找到 ID 为「{userId}」的用户！");
            return false;
        }

        _userList.Remove(userToDelete);
        Console.WriteLine($"删除成功：{userToDelete}");
        return true;
    }

    /// <summary>
    /// 更新用户信息
    /// </summary>
    public bool UpdateUser(User user)
    {
        if (user == null || user.Id <= 0)
        {
            Console.WriteLine("更新失败：用户对象不能为空且 ID 必须为正数！");
            return false;
        }

        User? existingUser = _userList.FirstOrDefault(u => u.Id == user.Id);

        if (existingUser == null)
        {
            Console.WriteLine($"更新失败：未找到 ID 为「{user.Id}」的用户！");
            return false;
        }

        // 校验用户名/邮箱冲突
        bool isUsernameConflict = _userList.Any(u => 
            u.Id != user.Id && u.Username.Equals(user.Username, StringComparison.OrdinalIgnoreCase));
        bool isEmailConflict = _userList.Any(u => 
            u.Id != user.Id && u.Email.Equals(user.Email, StringComparison.OrdinalIgnoreCase));

        if (isUsernameConflict)
        {
            Console.WriteLine($"更新失败：用户名「{user.Username}」已被占用！");
            return false;
        }

        if (isEmailConflict)
        {
            Console.WriteLine($"更新失败：邮箱「{user.Email}」已被占用！");
            return false;
        }

        // 更新信息
        existingUser.Username = user.Username;
        existingUser.Password = user.Password;
        existingUser.Email = user.Email;

        Console.WriteLine($"更新成功：{existingUser}");
        return true;
    }

    /// <summary>
    /// 根据 ID 查询单个用户
    /// </summary>
    public User? GetUserById(int userId)
    {
        User? user = _userList.FirstOrDefault(u => u.Id == userId);

        if (user == null)
        {
            Console.WriteLine($"查询失败：未找到 ID 为「{userId}」的用户！");
        }
        else
        {
            Console.WriteLine($"查询成功：{user}");
        }

        return user;
    }

    /// <summary>
    /// 查询所有用户
    /// </summary>
    public List<User> GetAllUsers()
    {
        if (!_userList.Any())
        {
            Console.WriteLine("查询结果：暂无用户数据！");
            return new List<User>();
        }

        Console.WriteLine($"查询成功：共找到 {_userList.Count} 个用户");
        foreach (var user in _userList)
        {
            Console.WriteLine(user);
        }

        return new List<User>(_userList); // 返回副本，避免外部修改原始数据
    }
}

/// <summary>
/// 测试程序入口
/// </summary>
class Text
{
    static void TextPrint(string[] args)
    {
        // 初始化服务（面向接口编程）
        IUserService userService = new UserServiceImpl();

        Console.WriteLine("=== 1. 新增用户 ===");
        userService.AddUser(new User { Username = "ZhangSan", Password = "123456", Email = "zhangsan@test.com" });
        userService.AddUser(new User { Username = "LiSi", Password = "654321", Email = "lisi@test.com" });
        Console.WriteLine();

        Console.WriteLine("=== 2. 查询所有用户 ===");
        userService.GetAllUsers();
        Console.WriteLine();

        Console.WriteLine("=== 3. 根据 ID 查询用户 ===");
        userService.GetUserById(1);
        Console.WriteLine();

        Console.WriteLine("=== 4. 更新用户 ===");
        userService.UpdateUser(new User { Id = 2, Username = "LiSi_Update", Password = "new123", Email = "lisi_update@test.com" });
        Console.WriteLine();

        Console.WriteLine("=== 5. 删除用户 ===");
        userService.DeleteUser(1);
        Console.WriteLine();

        Console.WriteLine("=== 6. 再次查询所有用户 ===");
        userService.GetAllUsers();

        // 阻止控制台关闭（按任意键退出）
        Console.WriteLine("\n按任意键退出...");
        Console.ReadKey();
    }
}
    
